iT邦幫忙

0

[Flutter ] Free fake API 為資料庫,以 FutureBuilder + http 抓取

  • 分享至 

  • xImage
  •  

程式版本: Flutter 2.2.1

使用JSONPlaceholder為 Free fake API 為資料庫,將其導入官方 FutureBuilder class 範例作為測試,並改 ListView 為瀏覽大量資料。

  1. JSONPlaceholder 資料內容:
[
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
  },
......
  1. 先在 pubspec.yaml 內加入 http,在此使用版本為 0.13.3。
dependencies:
  flutter:
    sdk: flutter
  http: ^0.13.3

官網說明需在 AndroidManifest.xml file 加入下指令,但進到檔案看時指令已存在。

<uses-permission android:name="android.permission.INTERNET" />
  1. 到 main.dart 修改 FutureBuilder class 範例入下:
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http; // 導入 http.get 抓資料
import 'dart:convert'; // 導入 jsonDecode 解壓資料

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  static const String _title = 'Flutter Code Sample';

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: _title,
      home: MyStatefulWidget(),
    );
  }
}

class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({Key? key}) : super(key: key);

  @override
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  // 原例: 延遲 2 秒後傳入 String 'Data Loaded'
  final Future<String> _calculation = Future<String>.delayed(
    const Duration(seconds: 2),
        () => 'Data Loaded',
  );

  // 輸入資料網址 令 http 抓取資料
  final String host = 'https://jsonplaceholder.typicode.com/posts';
  getData() {
    return http.get(Uri.parse(host)); // http 0.13 後不能直接輸入 string
  }

  @override
  Widget build(BuildContext context) {
    // 改為 Scaffold 輸出
    return Scaffold(
      appBar: AppBar(
        title: Text('FutureBuilder'),
      ),
      body: FutureBuilder(
        future: getData(), // 執行 http
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          // snapshot 抓資料,若優資料則:
          if (snapshot.hasData) {
            // jsonDecode 解壓
            List datas = jsonDecode(snapshot.data.body);

            return ListView.builder(
                itemCount: datas.length,
                itemBuilder: (context, idx) {
                  var data = datas[idx];
                  return ListTile(
                    title: Text(data['title']),
                    subtitle: Text(data['body']),
                  );
                });
          } else if (snapshot.hasError) {
            print('Error: ${snapshot.error}');
            return Container(); // 失敗回傳空資料
          } else {
            print('Awaiting result...');
            return Container();
          }
        },
      ),
    );
  }
}

  1. 輸出結果

註: 小白自學,歡迎評論指導!
參考資料:
https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html
https://www.youtube.com/watch?v=UGAmBMld6xE


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言